import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_video_course.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';

import 'course_catalogue_page.dart';
import 'course_introduce_page.dart';
import 'course_sign_page.dart';
import 'course_video_detail_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 视频课程详情
///代码清单
class MainCoursePage extends StatefulWidget {
  final BeanVideoCourse beanVideoCourse;

  /// 是否启用培训签到 on 开启；off 不开启
  final String openSign;

  ///培训签到
  final bool isTrainSign;
  final int trainId;
  final int taskId;

  const MainCoursePage(
      {Key key,
      @required this.beanVideoCourse,
      this.taskId,
      this.openSign = "off",
      this.isTrainSign = false,
      this.trainId})
      : super(key: key);

  @override
  _MainCoursePageState createState() => _MainCoursePageState();
}

class _MainCoursePageState extends State<MainCoursePage>
    with SingleTickerProviderStateMixin {
  //在这里标签页面使用的是TabView所以需要创建一个控制器
  TabController _tabController;

  //页面初始化方法
  @override
  void initState() {
    super.initState();
    if (widget.openSign == "on") {
      _tabController = new TabController(length: 3, vsync: this);
    } else {
      _tabController = new TabController(length: 2, vsync: this);
    }
    Future.delayed(Duration.zero, () {
      _getUserStudyInfo();
    });
  }

  //页面销毁回调生命周期
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  ///代码清单 5-19 NestedScrollView 下拉刷新
  ///lib/code/code5/example_504_CustomScrollView.dart
  @override
  Widget build(BuildContext context) {
    //构建页面的主体
    return Scaffold(
      //下拉刷新
      body: RefreshIndicator(
        //可滚动组件在滚动时会发送ScrollNotification类型的通知
        notificationPredicate: (ScrollNotification notifation) {
          //该属性包含当前ViewPort及滚动位置等信息
          ScrollMetrics scrollMetrics = notifation.metrics;
          if (scrollMetrics.minScrollExtent == 0) {
            return true;
          } else {
            return false;
          }
        },
        //下拉刷新回调方法
        onRefresh: () async {
          //模拟网络刷新 等待2秒
          await Future.delayed(Duration(milliseconds: 2000));
          //返回值以结束刷新
          return Future.value(true);
        },
        child: buildNestedScrollView(),
      ),
    );
  }

  ///代码清单 5-20 NestedScrollView 的创建
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildNestedScrollView() {
    //滑动视图
    return NestedScrollView(
      //配置可折叠的头布局
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [buildSliverAppBar()];
      },
      //页面的主体内容
      body: buidChildWidget(),
    );
  }

  ///代码清单 5-21 NestedScrollView 的创建
  ///lib/code/code5/example_504_CustomScrollView.dart
  //通常在用到 PageView + BottomNavigationBar 或者 TabBarView + TabBar 的时候
  //大家会发现当切换到另一页面的时候, 前一个页面就会被销毁, 再返回前一页时, 页面会被重建,
  //随之数据会重新加载, 控件会重新渲染 带来了极不好的用户体验.
  //由于TabBarView内部也是用的是PageView, 因此两者的解决方式相同
  //页面的主体内容
  Widget buidChildWidget() {
    if (widget.openSign == "on") {
      return TabBarView(
        controller: _tabController,
        children: <Widget>[
          CourseSignPage(
            beanVideoCourse: widget.beanVideoCourse,
            trainId: widget.trainId,
          ),
          CourseIntroducePage(
            beanVideoCourse: widget.beanVideoCourse,
            trainId: widget.trainId,
          ),
          CourseCataloguePage(
            beanVideoCourse: widget.beanVideoCourse,
            trainId: widget.trainId,
            taskId: widget.taskId,
          ),
          //CoursEevaluatePage(beanVideoCourse: widget.beanVideoCourse),
        ],
      );
    }
    return TabBarView(
      controller: _tabController,
      children: <Widget>[
        CourseIntroducePage(
          beanVideoCourse: widget.beanVideoCourse,
          trainId: widget.trainId,
        ),
        CourseCataloguePage(
          beanVideoCourse: widget.beanVideoCourse,
          trainId: widget.trainId,
          taskId: widget.taskId,
        ),
        //CoursEevaluatePage(beanVideoCourse: widget.beanVideoCourse),
      ],
    );
  }

  ///代码清单 5-22 SliverAppBar 的创建
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildSliverAppBar() {
    return SliverAppBar(
      //第一部分 标题 这里是搜索框
      title: Text("课程"),
      //标题居中
      centerTitle: true,
      //5.1.2小节中有对这一块的属性配置说明
      pinned: true,
      floating: false,
      snap: false,
      //阴影高度
      elevation: 1.0,
      //展开的高度
      expandedHeight: 240,
      //第二部分 AppBar下的内容区域
      flexibleSpace: FlexibleSpaceBar(
        //背景
        //配置的是一个widget也就是说在这里可以使用任意的
        //Widget组合 在这里直接使用的是一个图片
        background: buildFlexibleSpaceWidget(),
      ),
      //第三部分
      bottom: buildFlexibleTooBarWidget(),
    );
  }

  ///代码清单 5-23 构建SliverAppBar的标题title
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildHeader() {
    return Container(
      //宽度填充
      width: double.infinity,
      //左边距
      padding: EdgeInsets.only(left: 10),
      //高度限制
      height: 38,
      //圆角边框背景装饰
      decoration: BoxDecoration(
        //背景颜色
        color: Colors.white,
        //边框颜色
        border: Border.all(color: Colors.white),
        //边框圆角
        borderRadius: BorderRadius.circular(30),
      ),
      //左右排列的线性布局
      child: Row(
        //子Widget居中对齐
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          //一个搜索图片
          Icon(
            Icons.search_rounded,
            size: 18,
          ),
          SizedBox(
            width: 4,
          ),
          Text(
            "搜索",
            style: TextStyle(
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  ///代码清单 5-24 FlexibleSpaceBar 中的内容
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildFlexibleSpaceWidget() {
    //上下排列的线性布局
    return Stack(
      alignment: Alignment.center,
      children: [
        //第一部分是一个 轮播图
        Positioned.fill(
          child: Container(
            child: CachedNetworkImage(
              imageUrl: widget.beanVideoCourse.videoCourseImage,
              fit: BoxFit.fill,
            ),
          ),
        ),
        Positioned.fill(
          child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
            child: Container(
              color: Colors.white.withOpacity(0.9),
            ),
          ),
        ),
        InkWell(
          onTap: () {
            NavigatorUtils.pushPage(
                context,
                CourseVideoDetailsPage(
                  trainId: widget.trainId,
                  taskId: widget.taskId,
                  videoCourseId: widget.beanVideoCourse.id,
                ), callback: (value) {
              setState(() {});
            });

            if (!_isStudy) {
              //添加用户参与学习
              _addUserStudyFunction();
            }
          },
          child: Container(
            padding: EdgeInsets.only(left: 10, right: 10, top: 6, bottom: 6),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(4)),
              border: Border.all(color: Colors.green, width: 1.0),
            ),
            child: buildStartButton(),
          ),
        )
      ],
    );
  }

  Widget buildStartButton() {
    String studyText = "开始学习";
    if (_isStudy) {
      studyText = "继续学习";
    }
    return Text(
      studyText,
      style: TextStyle(
        color: Colors.green,
        fontSize: 16.0,
        fontWeight: FontWeight.w500,
      ),
    );
  }

  ///代码清单 5-26 [SliverAppBar]的bottom属性配制
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildFlexibleTooBarWidget() {
    //[PreferredSize]用于配置在AppBar或者是SliverAppBar
    //的bottom中 实现 PreferredSizeWidget
    return PreferredSize(
      //定义大小
      preferredSize: Size(MediaQuery.of(context).size.width, 44),
      //配置任意的子Widget
      child: Container(
        alignment: Alignment.center,
        child: Container(
          color: Colors.white,
          //随着向上滑动，TabBar的宽度逐渐增大
          //父布局Container约束为 center对齐
          //所以程现出来的是中间x轴放大的效果
          width: MediaQuery.of(context).size.width,
          child: TabBar(
            //指示线的宽度与文本宽度一致
            indicatorSize: TabBarIndicatorSize.label,
            //指示线的颜色
            indicatorColor: Colors.redAccent,
            //未选中文本的颜色
            unselectedLabelColor: Colors.grey,
            //选中文本的颜色
            labelColor: Colors.redAccent,
            controller: _tabController,
            tabs: buildTab(),
          ),
        ),
      ),
    );
  }

  List<Widget> buildTab() {
    if (widget.openSign == "on") {
      return <Widget>[
        new Tab(text: "签到"),
        new Tab(text: "介绍"),
        new Tab(text: "目录"),
        // new Tab(
        //   text: "评价",
        // ),
      ];
    }
    return <Widget>[
      new Tab(text: "介绍"),
      new Tab(text: "目录"),
      // new Tab(
      //   text: "评价",
      // ),
    ];
  }

  bool _isStudy = false;

  void _getUserStudyInfo() async {
    Map<String, dynamic> map = Map();
    map["videoCourseId"] = widget.beanVideoCourse.id;
    if (widget.isTrainSign) {
      map["trainId"] = widget.trainId;
    }
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.videoStudyInfoUrl, jsonMap: map, encrypt: true);

    if (responseInfo.success) {
      if (responseInfo.data != null) {
        _isStudy = true;
        setState(() {});
        //更新用户参与学习
        _addUserStudyFunction();
      }
    }
  }

  ///
  void _addUserStudyFunction() async {
    Map<String, dynamic> map = Map();
    map["videoCourseId"] = widget.beanVideoCourse.id;
    if (widget.isTrainSign) {
      map["trainId"] = widget.trainId;
    }
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.videoStudyAddUrl, jsonMap: map, encrypt: true);
    _isStudy = true;
  }
}
